<template>
    <div class="dropdown-container" ref="containerRef">
        <img
            :src="icon"
            :alt="alt"
            class="icon-hover transition"
            :class="theme.isDark ? 'text-light' : 'text-dark'"
            style="height: 30px; cursor: pointer"
            :title="title"
            @click="toggleDropdown"
        />
        <div v-if="visible" class="dropdown-menu show mt-2">
            <template v-for="(item, index) in items" :key="index">
                <div v-if="item.divider" class="dropdown-divider"></div>
                <RouterLink v-else-if="item.to" class="dropdown-item" :to="item.to" @click="visible = false">
                    {{ item.label }}
                </RouterLink>
                <a
                    v-else
                    href="#"
                    class="dropdown-item"
                    :class="{ 'text-danger': item.danger }"
                    @click.prevent="handleCustomAction(item.action)"
                >
                    {{ item.label }}
                </a>
            </template>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { useThemeStore } from '../../store/theme';

defineProps({
    icon: String,
    alt: String,
    title: String,
    items: Array // 支持 to、action、divider、danger
});

const theme = useThemeStore();
const visible = ref(false);
const containerRef = ref(null);

const toggleDropdown = () => {
    visible.value = !visible.value;
};

const handleClickOutside = e => {
    if (containerRef.value && !containerRef.value.contains(e.target)) {
        visible.value = false;
    }
};

const handleCustomAction = fn => {
    visible.value = false;
    fn?.();
};

onMounted(() => document.addEventListener('click', handleClickOutside));
onBeforeUnmount(() => document.removeEventListener('click', handleClickOutside));
</script>

<style scoped>
.dropdown-container {
    position: relative;
}

.dropdown-menu {
    min-width: 160px;
    position: absolute;
    right: 0;
    left: auto;
    z-index: 999;
    background-color: var(--bs-body-bg);
    border: 1px solid var(--bs-border-color-translucent);
    border-radius: 0.375rem;
    box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.1);
}
</style>
